import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author: shiding
 * @data: 2022/5/22 11:24
 **/
public class ThreeSum {

    public static void main(String[] args) {
        int nums[] = {-1,0,1,2,-1,-4};
        threeSum(nums);
    }

    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> l = new ArrayList();
        if (nums == null || nums.length < 3) {
            return l;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length;i++) {
            if (nums[i] > 0) {
                break;
            }
            if(i > 0 && nums[i] == nums[i-1]) continue;
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                int ld = nums[left];
                int rd = nums[right];
                int sum = nums[i] + nums[left] + nums[right];
                if (sum < 0) {left++;}
                if (sum > 0){right--;}
                if (sum == 0) {
                    l.add(Arrays.asList(nums[i], nums[left],nums[right]));
                    while(left < right && nums[right] == rd){
                        right--;
                    }
                    while (left < right && nums[left] == ld){
                        left++;
                    }
                }
            }
        }
        return l;
    }
}
